package com.jb.web.bean.custom.renderer;

import com.jb.web.application.PageSecurityException;
import com.jb.web.bean.Panel;
import com.jb.web.bean.Page;
import com.jb.web.context.WebContext;
import com.jb.web.renderer.FloatPanelRenderer;

import com.jb.faces.component.UIComponent;
import com.jb.web.bean.FloatPanel;


/**
 * Renders a panel that embeds another page. Through property
 * embedded. If the page not found, nothing would happen.
 *
 * The page itself does not go through full life cycle within this component.
 * It merely displays the page. It is important to have the resuable page
 * coded so that it is url igornostic, use ${context.pageName}.xsp should
 * solve the problem
 * */
public class ReuseRegionRenderer extends FloatPanelRenderer {
    public StringBuffer renderChildren(WebContext pCtx, UIComponent item) {
        FloatPanel hItem = (FloatPanel) item;
        StringBuffer htmlBuffer = new StringBuffer();
        String pageName = hItem.getEmbedded();

        if (pageName != null) {
            try {
                if (pCtx.isRunTime() || !hItem.getPage().isDesignable()) {
                    Page page = pCtx.getSession().getPage(pCtx, pageName, true);

                    if (page != null) {
                        boolean oldDesignable = page.isDesignable();
                        page.setEmbedded(true);
                        page.setDesignable(false);
                        page.setContained(hItem);
                        htmlBuffer.append(page.render(pCtx));
                        page.setContained(null);
                        page.setDesignable(oldDesignable);
                        page.setEmbedded(false);
                    }
                } else {
                    htmlBuffer.append(pageName + " is embedded here");
                }
            } catch (PageSecurityException e) {
            }
        }

        return htmlBuffer;
    }
}
